<?php

class td_js_buffer {
    static $js_header_buffer = '';
    static $js_variables_buffer = '';
    static $js_footer_buffer = ''; //js buffer for the footer

    static function add($js) {
        self::$js_header_buffer .= "\n" . $js;
    }

    static function add_to_footer($js) {
        self::$js_footer_buffer .= "\n" . $js;
    }


    static function add_variable($var, $value) {
        self::$js_variables_buffer .= "\n" .'var ' . $var . '="' . $value . '";';
    }

    //renders the variables + custom js
    static function render() {
        return "\n<!-- JS generated by theme -->" . "\n\n<script>\n    " . apply_filters("td_js_buffer_render",  self::$js_header_buffer . self::$js_variables_buffer) . "\n</script>\n\n";
    }

    //renders the footer js
    static function render_footer() {
        return "\n<!-- JS generated by theme -->" . "\n\n<script>\n    " . apply_filters("td_js_buffer_footer_render",  self::$js_footer_buffer) . "\n</script>\n\n";
    }

    //renders only the variables - used in wp-admin
    static function render_variables() {
        return "\n<!-- JS generated by theme -->" . "\n\n<script>\n    " . self::$js_variables_buffer . "\n</script>\n\n";
    }


}


function td_js_buffer_render() {
    echo td_js_buffer::render();
}

function td_js_variables_render() {
    echo td_js_buffer::render_variables();
}

function td_js_buffer_footer_render() {
    echo td_js_buffer::render_footer();
}

//load the entire js in front end
add_action('wp_head', 'td_js_buffer_render', 15);

//load only the variables in wp-admin
add_action('admin_head', 'td_js_variables_render', 15);


//load only the variables in wp-admin
add_action('wp_footer', 'td_js_buffer_footer_render', 100);